package com.houger.ddd.seckill.template.holder;
import com.houger.ddd.seckill.infra.entity.ActivityTemplateBasic;
import com.houger.ddd.seckill.template.ActivityTemplate;
import com.houger.ddd.seckill.template.service.ActivityTemplateService;
import jakarta.annotation.Resource;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class BeanHolder implements ApplicationContextAware {

    @Getter
    private ApplicationContext applicationContext = null;

    private final Map<String, Object> beanMap = new ConcurrentHashMap<>();

    @Resource
    private ActivityTemplateService activityTemplateService;

    @Override
    public void setApplicationContext(ApplicationContext context) {
        this.applicationContext = context;
    }

    public <T> T getBean(Class<T> clazz) {
        String key = clazz.getName();
        if (beanMap.containsKey(key)) {
            return (T) beanMap.get(key);
        }
        synchronized (beanMap) {
            if (beanMap.containsKey(key)) {
                return (T) beanMap.get(key);
            }
            final T bean = this.getApplicationContext().getBean(clazz);
            beanMap.put(key, bean);
            return bean;
        }
    }


    public ActivityTemplate getTemplate(final Long id) {
        final ActivityTemplateBasic activityTemplateBasic = activityTemplateService.queryBasicById(id);
        try {
            return  (ActivityTemplate)this.getApplicationContext().getBean(Class.forName(activityTemplateBasic.getTemplateTypeClass()));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public ActivityTemplate getTemplate(final String templateTypeClass) {
        try {
            return (ActivityTemplate)this.getApplicationContext().getBean(Class.forName(templateTypeClass));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

}
